package cn.com.connected.service.impl;

import cn.com.connected.base.exception.BusinessException;
import cn.com.connected.base.exception.ErrorCode;
import cn.com.connected.common.emnus.ScopeType;
import cn.com.connected.common.utils.JwtUtil;
import cn.com.connected.service.TokenService;
import cn.com.connected.vo.base.TokenVO;
import lombok.extern.log4j.Log4j2;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;

import java.util.Date;

import static cn.com.connected.common.emnus.HttpParams.BEARER;


/**
 * @program: sameway-server
 * @description:
 * @author: 邵明生
 * @create: 2019-03-18 10:14
 **/
@Service
@Log4j2
public class TokenServiceImpl implements TokenService {

    @Resource
    private JwtUtil jwtUtil;

    public static TokenService tokenService;

    @PostConstruct
    public void init() {
        tokenService = this;
    }

    @Override
    public String createToken(TokenVO tokenVO) {
        return jwtUtil.createJWT(tokenVO);
    }

    @Override
    public String createToken(String userId) {
        TokenVO tokenVO = new TokenVO(userId, ScopeType.school_wx.getValue(), new Date(),30*24*60*60l);
        String token = tokenService.createToken(tokenVO);
        return token;
    }

    @Override
    public TokenVO parseToken(String token) {
        if (StringUtils.isEmpty(token)){
            log.info("token:"+token);
            throw new BusinessException(ErrorCode.LOGIN_NO_TICKET);
        }
        token = token.replace(BEARER,"");
        return jwtUtil.parseJwtToBean(token);
    }
}
